package com.bodacn.keypoint;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;

import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.bodacn.keypoint.MainApplication.TermNo;

public class ReceiveActivity extends AppCompatActivity implements View.OnClickListener {
    private String TAG=this.getClass().getName();
    private final int MSG_DetailOver=1001;
    private final int MSG_MasterOver =1002;
    private  final int MSG_ERRMSG = 1003;
    private  final int MSG_ReceiveOver = 1004;

    String STORE_NAME = "Settings";
    String curLoginUserNo,curLoginUser,curServiceUrl="",curServiceDir="",curDepartNo,curDepart,CPUID;
    ListView detailList,masterList;
    JSONArray detailJson,masterJson,resultJson;
    Toast curToast;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_receive);
        hideBottomUIMenu();
        //获取登陆参数
        Bundle paramBundle = this.getIntent().getExtras();
        curLoginUserNo=paramBundle.getString("LoginUserNo","");
        curLoginUser=paramBundle.getString("LoginUser","");
        curDepartNo=paramBundle.getString("CurDepartNo","");
        curDepart=paramBundle.getString("CurDepart","");
        curServiceUrl=paramBundle.getString("ServiceUrl","");
        curServiceDir=paramBundle.getString("ServiceDir","");
        CPUID=paramBundle.getString("CPUID","");
        //界面信息
        masterList=findViewById(R.id.masterList);
        masterList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (masterJson.optJSONObject(position).has("ZydMaID")){
                    try {
                        String ZydMaID=masterJson.optJSONObject(position).getString("ZydMaID");
                        GetDetailData(ZydMaID);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        detailList=findViewById(R.id.detailList);
        System.out.println(paramBundle);
        //初始化界面
        findViewById(R.id.btn_return).setOnClickListener(this);
        findViewById(R.id.btn_receive).setOnClickListener(this);
        findViewById(R.id.btn_refresh).setOnClickListener(this);
        //初始提醒;
        curToast = Toast.makeText(this, "", Toast.LENGTH_SHORT);
    }


    /**
     * 隐藏虚拟按键，并且全屏
     */
    protected void hideBottomUIMenu() {
        //隐藏状态栏和底部虚拟按键
        View decorView = getWindow().getDecorView();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            int flag = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
            decorView.setSystemUiVisibility(flag);
        }
    }
    // 隐藏手机键盘
    private void hideIM(View edt) {
        try {
            InputMethodManager im = (InputMethodManager) getApplicationContext().getSystemService(Activity.INPUT_METHOD_SERVICE);
            IBinder windowToken = edt.getWindowToken();
            if (windowToken != null) {
                im.hideSoftInputFromWindow(windowToken, 0);
            }
        } catch (Exception e) {

        }
    }

    @Override
    public void onClick(View v) {
        hideIM(v);
        switch (v.getId()){
            case R.id.btn_refresh:
                GetMasterData();
                break;
            case R.id.btn_receive:
                if (masterList.getCheckedItemPosition()>-1) {
                    try {
                        String ZydMaID=masterJson.optJSONObject(masterList.getCheckedItemPosition()).getString("ZydMaID");
                        ReceiveData(ZydMaID);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else{
                    curToast.setText("请选择需要接收的转移单");
                    curToast.show();
                }
                break;
            case R.id.btn_return:
                finish();
                break;
            default:
                break;
        }
    }

    //获取明细;
    private void GetMasterData() {
        try {
            masterJson = new JSONArray("[]");
            //显示明细数据
            MasterListAdapter masterListAdapter=new MasterListAdapter(getApplicationContext());
            masterList.setAdapter(masterListAdapter);
            detailJson = new JSONArray("[]");
            //显示明细数据
            DetailListAdapter detailListAdapter=new DetailListAdapter(getApplicationContext());
            detailList.setAdapter(detailListAdapter);
        } catch (Exception e){
            e.printStackTrace();
        }
        String sqlCmd="Exec KeyPoint_GetZydList @OperType='Master',@DepartNo='"+curDepartNo+"',@TermNo='"+TermNo
                +"',@UserNo='" + curLoginUserNo + "',@CPUID='" + CPUID + "'";
        ReadSQLData(sqlCmd);

    }

    @Override
    protected void onResume() {
        super.onResume();
        GetMasterData();
    }

    //获取明细;
    private void GetDetailData(String paramZydMaID) {
        try {
            detailJson = new JSONArray("[]");
            //显示明细数据
            DetailListAdapter detailListAdapter=new DetailListAdapter(getApplicationContext());
            detailList.setAdapter(detailListAdapter);
        } catch (Exception e){
            e.printStackTrace();
        }
        String sqlCmd="Exec KeyPoint_GetZydList @OperType='Detail',@ZydMaID='"+paramZydMaID
                +"',@DepartNo='"+curDepartNo+"',@TermNo='"+TermNo
                +"',@UserNo='" + curLoginUserNo + "',@CPUID='" + CPUID + "'";
        ReadSQLData(sqlCmd);

    }

    private void ReceiveData(String paramZydMaID) {
        String sqlCmd="Exec KeyPoint_GetZydList @OperType='Receive',@ZydMaID='"+paramZydMaID
                +"',@DepartNo='"+curDepartNo+"',@TermNo='"+TermNo
                +"',@UserNo='" + curLoginUserNo + "',@CPUID='" + CPUID + "'";
        ReadSQLData(sqlCmd);

    }



    //直接连获取数据，与Handler配套使用;
    private void ReadSQLData ( final String SQLComm){
        System.out.println("SQLComm:"+SQLComm);
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try {
                    JSONArray jsonArray = DBUtil.QuerySQL2JSON(SQLComm);
                    System.out.println(jsonArray);
                    String OperType="";
                    //往界面转数据;
                    if ((jsonArray != null) && (jsonArray.length() > 0)) {
                        if (jsonArray.optJSONObject(0).has("OperType")==true)  OperType=jsonArray.optJSONObject(0).getString("OperType");
                        if (jsonArray.optJSONObject(0).has("OPERTYPE")==true)  OperType=jsonArray.optJSONObject(0).getString("OPERTYPE");
                        //呼叫信息及库存警告
                        if (OperType.equals("Master") == true) {
                            masterJson = jsonArray;
                            //显示预排单;
                            Message msg = new Message();
                            msg.what = MSG_MasterOver;
                            handler.removeMessages(msg.what);
                            handler.sendMessage(msg);
                        }
                        if (OperType.equals("Detail") == true) {
                            detailJson= jsonArray;
                            //显示预排单;
                            Message msg = new Message();
                            msg.what = MSG_DetailOver;
                            handler.removeMessages(msg.what);
                            handler.sendMessage(msg);
                        }
                        if (OperType.equals("Receive") == true) {
                            resultJson= jsonArray;
                            //显示预排单;
                            Message msg = new Message();
                            msg.what = MSG_ReceiveOver;
                            handler.removeMessages(msg.what);
                            handler.sendMessage(msg);
                        }
                        //SQL异常;
                        if (jsonArray.optJSONObject(0).has("SQLExcept")==true)  {
                            //关闭ProgressDialog
                            Message msg = new Message();
                            msg.what = MSG_ERRMSG;
                            Bundle bundle=new Bundle();
                            bundle.putString("MSG",jsonArray.optJSONObject(0).getString("SQLMessage"));
                            msg.setData(bundle);
                            handler.removeMessages(msg.what);
                            handler.sendMessage(msg);
                            return;
                        }
                    } else{
                        //关闭ProgressDialog
                        Message msg = new Message();
                        msg.what = MSG_ERRMSG;
                        Bundle bundle=new Bundle();
                        bundle.putString("MSG","未返回数据");
                        msg.setData(bundle);
                        handler.removeMessages(msg.what);
                        handler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

        };
        new Thread(run).start();

    }




    //通过消息来执行处理类程序,不更新UI则不一定需要通过这个;
    final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            // TODO Auto-generated method stub
            // 根据消息ID来判断要做的事情
            int msgId = msg.what;
            switch (msgId) {
                case MSG_ERRMSG:
                    Bundle bundle=msg.getData();
                    new AlertDialog.Builder(masterList.getContext())
                            .setTitle(getString(R.string.SystemHint)).setMessage(bundle.getString("MSG"))
                            .setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                }
                            }).create().show();
                    break;
                case MSG_MasterOver:
                    //显示明细数据
                    MasterListAdapter masterListAdapter=new MasterListAdapter(getApplicationContext());
                    masterList.setAdapter(masterListAdapter);
                    break;
                case MSG_DetailOver:
                    //显示明细数据
                    DetailListAdapter detailListAdapter=new DetailListAdapter(getApplicationContext());
                    detailList.setAdapter(detailListAdapter);
                    break;
                case MSG_ReceiveOver:
                    if (resultJson!=null&&resultJson.length()>0) {
                        try {
                            if (resultJson.getJSONObject(0).has("ErrInfo") == true) {
                                AlertDialog alertDialog = new AlertDialog.Builder(masterList.getContext())
                                        .setTitle("系统提示").setMessage(resultJson.getJSONObject(0).getString("ErrInfo"))
                                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog, int which) {
                                                hideBottomUIMenu();
                                                return;
                                            }
                                        }).create(); // 创建对话框
                                alertDialog.show(); // 显示对话框
                            } else
                            if (resultJson.getJSONObject(0).has("ResultInfo") == true) {
                                curToast.setText(resultJson.getJSONObject(0).getString("ResultInfo"));
                                curToast.show();
                            }
                            if (resultJson.getJSONObject(0).has("LoadData") == true) {
                                if (resultJson.getJSONObject(0).getString("LoadData").equals("Y"))
                                    GetMasterData();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    break;
                default:
                    break;
            }
        }
    };



    //员工状态表格适配器;
    public final class MasterListAdapter extends BaseAdapter {
        private LayoutInflater inflater;

        public MasterListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public int getCount() {
            return masterJson.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return masterJson.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View conView = inflater.inflate(R.layout.activity_receive_zydma_head, null, false);
            int textColor = getResources().getColor(R.color.text_black);
            try {
                Log.d("msg", "getView()----------------------------------------------------->" + position);
                if (masterJson.optJSONObject(position).has("ConColor")) {
                    textColor = GetColorValue(masterJson.optJSONObject(position).getString("ConColor"));
                }
                TextView tv = (TextView) conView.findViewById(R.id.txt_Zydh);// 显示文字
                if (masterJson.optJSONObject(position).has("Zydh"))
                    tv.setText(masterJson.optJSONObject(position).get("Zydh").toString());
                tv.setTextColor(textColor);
                tv = (TextView) conView.findViewById(R.id.txt_RecState);// 显示文字
                if (masterJson.optJSONObject(position).has("RecState"))
                    tv.setText(masterJson.optJSONObject(position).get("RecState").toString());
                tv.setTextColor(textColor);
            } catch (JSONException e) {
                e.printStackTrace();
                curToast.setText(e.getMessage());
                curToast.show();
            }
            Log.d("msg", "MasterListAdapter_position:" + position);
            return conView;
        }


    }

    //员工状态表格适配器;
    public final class DetailListAdapter extends BaseAdapter {
        private LayoutInflater inflater;

        public DetailListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public int getCount() {
            return detailJson.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return detailJson.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View conView = inflater.inflate(R.layout.activity_receive_zydde_head, null, false);
            int textColor = getResources().getColor(R.color.text_black);
            try {
                Log.d("msg", "getView()----------------------------------------------------->" + position);
                if (detailJson.optJSONObject(position).has("ConColor")) {
                    textColor = GetColorValue(detailJson.optJSONObject(position).getString("ConColor"));
                }
                TextView tv = (TextView) conView.findViewById(R.id.txt_NeedDate);// 显示文字
                if (detailJson.optJSONObject(position).has("NeedDate"))
                    tv.setText(detailJson.optJSONObject(position).get("NeedDate").toString());
                tv.setTextColor(textColor);
                tv = (TextView) conView.findViewById(R.id.txt_DBH);// 显示文字
                if (detailJson.optJSONObject(position).has("DBH"))
                    tv.setText(detailJson.optJSONObject(position).get("DBH").toString());
                tv.setTextColor(textColor);
                tv = (TextView) conView.findViewById(R.id.txt_PO);// 显示文字
                if (detailJson.optJSONObject(position).has("PO"))
                    tv.setText(detailJson.optJSONObject(position).get("PO").toString());
                tv.setTextColor(textColor);
                tv = (TextView) conView.findViewById(R.id.txt_OrderNo);// 显示文字
                if (detailJson.optJSONObject(position).has("OrderNo"))
                    tv.setText(detailJson.optJSONObject(position).get("OrderNo").toString());
                tv.setTextColor(textColor);
                tv = (TextView) conView.findViewById(R.id.txt_StyleNo);// 显示文字
                if (detailJson.optJSONObject(position).has("StyleNo"))
                    tv.setText(detailJson.optJSONObject(position).get("StyleNo").toString());
                tv.setTextColor(textColor);
                tv = (TextView) conView.findViewById(R.id.txt_StyleSort);// 显示文字
                if (detailJson.optJSONObject(position).has("StyleSort"))
                    tv.setText(detailJson.optJSONObject(position).get("StyleSort").toString());
                tv.setTextColor(textColor);
                tv = (TextView) conView.findViewById(R.id.txt_PartName);// 显示文字
                if (detailJson.optJSONObject(position).has("PartName"))
                    tv.setText(detailJson.optJSONObject(position).get("PartName").toString());
                tv.setTextColor(textColor);
                tv = (TextView) conView.findViewById(R.id.txt_ColorNo);// 显示文字
                if (detailJson.optJSONObject(position).has("ColorNo"))
                    tv.setText(detailJson.optJSONObject(position).get("ColorNo").toString());
                tv.setTextColor(textColor);
                tv = (TextView) conView.findViewById(R.id.txt_Color);// 显示文字
                if (detailJson.optJSONObject(position).has("Color"))
                    tv.setText(detailJson.optJSONObject(position).get("Color").toString());
                tv.setTextColor(textColor);
                tv = (TextView) conView.findViewById(R.id.txt_Size);// 显示文字
                if (detailJson.optJSONObject(position).has("Size"))
                    tv.setText(detailJson.optJSONObject(position).get("Size").toString());
                tv.setTextColor(textColor);
                tv = (TextView) conView.findViewById(R.id.txt_NeedNum);// 显示文字
                if (detailJson.optJSONObject(position).has("NeedNum"))
                    tv.setText(detailJson.optJSONObject(position).get("NeedNum").toString());
                tv.setTextColor(textColor);
                tv = (TextView) conView.findViewById(R.id.txt_RealNum);// 显示文字
                if (detailJson.optJSONObject(position).has("RealNum"))
                    tv.setText(detailJson.optJSONObject(position).get("RealNum").toString());
                tv.setTextColor(textColor);

            } catch (JSONException e) {
                e.printStackTrace();
                curToast.setText(e.getMessage());
                curToast.show();
            }
            Log.d("msg", "MasterListAdapter_position:" + position);
            return conView;
        }


    }

    //从字符串转颜色
    private int GetColorValue(String paramColor){
        int PenColor= Color.WHITE;
        String StrPenColor=paramColor;
        if ((StrPenColor.indexOf("#")==0)&&(StrPenColor.length()==7)){
            int testColor=Integer.parseInt(StrPenColor.substring(1),16);
            int red = (testColor & 0xff0000) >> 16;
            int green = (testColor & 0x00ff00) >> 8;
            int blue = (testColor & 0x0000ff);
            PenColor=Color.rgb(red, green, blue);
        }else {
            if (isNumer(StrPenColor)) {
                int testColor = Integer.parseInt(StrPenColor);
                int red = (testColor & 0xff0000) >> 16;
                int green = (testColor & 0x00ff00) >> 8;
                int blue = (testColor & 0x0000ff);
                PenColor = Color.rgb(red, green, blue);
            } else {
                if (StrPenColor.equals("Black") == true)
                    PenColor = Color.BLACK;
                if (StrPenColor.equals("Blue") == true)
                    PenColor = Color.BLUE;
                if (StrPenColor.equals("Yellow") == true)
                    PenColor = Color.YELLOW;
                if (StrPenColor.equals("Red") == true)
                    PenColor = Color.RED;
                if (StrPenColor.equals("Green") == true)
                    PenColor = Color.GREEN;
                if (StrPenColor.equals("Gray") == true)
                    PenColor = Color.LTGRAY;
                if (StrPenColor.equals("White") == true)
                    PenColor = Color.WHITE;
            }
        }
        return PenColor;
    }
    //判断是否为数字
    public static boolean isNumer(String str) {
        Pattern pattern = Pattern.compile("-?[0-9]+\\.?[0-9]+");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }
}
